package com.example.study.service.impl;

import com.auth0.jwt.JWT;
import com.example.study.entity.LoginUser;
import com.example.study.entity.Result;
import com.example.study.pojo.Menu;
import com.example.study.pojo.User;
import com.example.study.service.LoginService;
import com.example.study.service.UserService;
import com.example.study.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userSevice;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        //AuthenticationManger authenticate进行用户认证,
        //用户信息封装成Authentication作为authenticate（）方法参数
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证失败，给出提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户认证失败");
        }
        //获取用户信息UserDetails,LoginUser实现了UserDetails接口
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        //认证通过，用户信息生成token
        Map<String, String> params = new HashMap<>();
        params.put("account", principal.getUser().getAccount());
        params.put("username", principal.getUser().getUsername());
        String token = JWTUtil.getToken(params);
        //把User信息存入redis中，减少数据库查询操作,存入LogingUser会造成redis获取时JSON格式转换失效
        redisTemplate.opsForValue().set("login:"+principal.getUser().getAccount(),principal);
        //获取菜单
        List<Menu> menu = userSevice.getMenu(user.getAccount());
        //返回前端数据token
        Map<String, Object> params1 = new HashMap<>();
        params1.put("token",token);
        params1.put("menuList",menu);
        return Result.ok(params1);
    }

    @Override
    public Result logout() {
        //SecurityContextHolder.getContext().getAuthentication()获取安全上下文获取Authentication对象
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String redisKey="login:"+loginUser.getUser().getAccount();
        redisTemplate.delete(redisKey);
        return Result.ok("退出成功");
    }
}
